package com.fc.mall.portal.wechat;

import com.fc.mall.portal.wechat.dto.WxConfig;
import org.apache.commons.codec.digest.DigestUtils;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.SortedMap;

import org.jdom2.Document;
import org.jdom2.JDOMException;
import org.jdom2.input.SAXBuilder;
import org.jdom2.Element;

/**
 * Created by Sunny on 2019/4/25.
 */
public class PaymentCommonUtil {
    /**
     * 正常支付创建签名
     * @param wxConfig
     * @param nonceStr
     * @param body
     * @param openid
     * @param out_trade_no
     * @param spbill_create_ip
     * @param totalFee
     * @return
     */
    public static String createSign(WxConfig wxConfig, String nonceStr, String body, String openid, String out_trade_no, String spbill_create_ip, String totalFee)
    {
        String appid = wxConfig.getAppId();
        String mch_id = wxConfig.getMchId();

        String assicOrderStr = "appid=%s&body=%s&mch_id=%s&nonce_str=%s&notify_url=%s&openid=%s&out_trade_no=%s&spbill_create_ip=%s&total_fee=%s&trade_type=%s";
        String stringSignTemp=String.format(assicOrderStr, appid,body,mch_id,nonceStr, wxConfig.getNotifyUrl(), openid, out_trade_no, spbill_create_ip, totalFee ,wxConfig.getTradeType())+"&key="+wxConfig.getPayKey();
        String sign= DigestUtils.md5Hex(stringSignTemp).toUpperCase();
        return sign;
    }


    /**
     * 微信服务商支付创建签名
     * @param wxConfig
     * @param nonceStr
     * @param body
     * @param openid
     * @param out_trade_no
     * @param spbill_create_ip
     * @param totalFee
     * @return
     */
    public static String createSignForWsp(WxConfig wxConfig, String nonceStr, String body, String openid, String out_trade_no, String spbill_create_ip, String totalFee)
    {
        String appid = wxConfig.getAppId();
        String mch_id = wxConfig.getMchId();
        String subAppid = wxConfig.getSubAppId();
        String submchId = wxConfig.getSubMchId();

        String assicOrderStr = "appid=%s&body=%s&mch_id=%s&nonce_str=%s&notify_url=%s&out_trade_no=%s&spbill_create_ip=%s&sub_appid=%s&sub_mch_id=%s&sub_openid=%s&total_fee=%s&trade_type=%s";
        String stringSignTemp=String.format(assicOrderStr, appid,body,mch_id,nonceStr, wxConfig.getNotifyUrl(), out_trade_no, spbill_create_ip,subAppid, submchId, openid, totalFee ,wxConfig.getTradeType())+"&key=" + wxConfig.getPayKey();
        String sign= DigestUtils.md5Hex(stringSignTemp).toUpperCase();
        return sign;
    }

    public static String createSignWithAttach(WxConfig wxConfig, String attach, String nonceStr, String body,String openid, String out_trade_no,  String spbill_create_ip, String totalFee)
    {
        String appid = wxConfig.getAppId();
        String mch_id = wxConfig.getMchId();

        String assicOrderStr = "appid=%s&attach=%s&body=%s&mch_id=%s&nonce_str=%s&notify_url=%s&openid=%s&out_trade_no=%s&spbill_create_ip=%s&total_fee=%s&trade_type=%s";
        String stringSignTemp=String.format(assicOrderStr, appid, attach, body,mch_id, nonceStr, wxConfig.getNotifyUrl(), openid, out_trade_no, spbill_create_ip, totalFee ,wxConfig.getTradeType())+"&key="+wxConfig.getPayKey();
        String sign=DigestUtils.md5Hex(stringSignTemp).toUpperCase();
        return sign;
    }

    public static String getRequestXml(SortedMap<Object, Object> parameters)
    {
        StringBuffer sb = new StringBuffer();
        sb.append("<xml>");
        Set es = parameters.entrySet();
        Iterator it = es.iterator();
        while (it.hasNext())
        {
            Map.Entry entry = (Map.Entry) it.next();
            String k = (String) entry.getKey();
            String v = (String) entry.getValue();
            if ("attach".equalsIgnoreCase(k) || "body".equalsIgnoreCase(k) || "sign".equalsIgnoreCase(k))
            {
                sb.append("<" + k + ">" + "<![CDATA[" + v + "]]></" + k + ">");
            }
            else
            {
                sb.append("<" + k + ">" + v + "</" + k + ">");
            }
        }
        sb.append("</xml>");
        return sb.toString();
    }

    public static Map doXMLParse(String strxml) throws JDOMException, IOException
    {
        strxml = strxml.replaceFirst("encoding=\".*\"", "encoding=\"UTF-8\"");

        if (null == strxml || "".equals(strxml))
        {
            return null;
        }

        Map m = new HashMap();

        InputStream in = new ByteArrayInputStream(strxml.getBytes("UTF-8"));
        SAXBuilder builder = new SAXBuilder();
        Document doc = builder.build(in);
        Element root = doc.getRootElement();
        List list = root.getChildren();
        Iterator it = list.iterator();
        while (it.hasNext())
        {
            Element e = (Element) it.next();
            String k = e.getName();
            String v = "";
            List children = e.getChildren();
            if (children.isEmpty())
            {
                v = e.getTextNormalize();
            }
            else
            {
                v = getChildrenText(children);
            }

            m.put(k, v);
        }

        // 关闭流
        in.close();

        return m;
    }

    public static String getChildrenText(List children)
    {
        StringBuffer sb = new StringBuffer();
        if (!children.isEmpty())
        {
            Iterator it = children.iterator();
            while (it.hasNext())
            {
                Element e = (Element) it.next();
                String name = e.getName();
                String value = e.getTextNormalize();
                List list = e.getChildren();
                sb.append("<" + name + ">");
                if (!list.isEmpty())
                {
                    sb.append(getChildrenText(list));
                }
                sb.append(value);
                sb.append("</" + name + ">");
            }
        }

        return sb.toString();
    }
}
